package fr.matwizz.mesdevoirs.android.task.impl;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import fr.matwizz.mesdevoirs.android.callback.TaskCallback;
import fr.matwizz.mesdevoirs.android.task.AbstractTask;
import fr.matwizz.mesdevoirs.serveur.model.Agenda;

/**
 * Created by Fixe on 27/04/14.
 */
public class RetrieveAgendaTask extends AbstractTask<Agenda> {

    public RetrieveAgendaTask(TaskCallback<Agenda> call) {
        super(call);
    }

    @Override
    protected Agenda doInBackground(String... strings) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(strings[0]);
        HttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
                Agenda agenda = getGson().fromJson(streamReader, Agenda.class);
                return agenda;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Agenda agenda) {
        callback.callback(agenda);
    }
}
